package config

import (
	"fmt"
	"github.com/urfave/cli/v2"
	"gitlab-dingtalk/server/config/db"
	"gitlab-dingtalk/server/config/logger"
	"gopkg.in/yaml.v3"
	"io/ioutil"
)

var instance *ApplicationConfig

type Configuration struct {
	FilePath   string
	CliContext *cli.Context
}

type Server struct {
	HostPort string `yaml:"hostPort"`
}

type ApplicationConfig struct {
	Server       *Server              `yaml:"server"`
	Datasource   *db.Datasource       `yaml:"datasource"`
	LoggerConfig *logger.LoggerConfig `yaml:"logger"`
}

func Config() *ApplicationConfig {
	return instance
}

func (o Configuration) GetApplicationConfig() *ApplicationConfig {
	if instance != nil {
		return instance
	}
	fmt.Println("开始载入配置")
	instance = &ApplicationConfig{}
	if yamlFile, err := ioutil.ReadFile(o.FilePath); err != nil {
		fmt.Println("文件 配置没找到 路径")
		return o.getDefaultApplicationConfig()
	} else if err = yaml.Unmarshal(yamlFile, instance); err != nil {
		return o.getDefaultApplicationConfig()
	}
	fmt.Println("找到配置 并且载入完成")
	return instance
}

func (o Configuration) getDefaultApplicationConfig() *ApplicationConfig {
	// 从 指令里面获取 hostPort 端口监听
	instance.Server.HostPort = o.CliContext.String("hostPort")
	return instance
}
